package com.example.s05_shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.s05_shop.pojo.Admin;
import com.example.s05_shop.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// @RestController  =   @Controller + @ResponseBody

@Controller
@RequestMapping("/admin/")
public class AdminController
{
    @Autowired
    private IAdminService adminService;


    @RequestMapping("/")
    public String index(HttpSession session)
    {
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin==null)
        {
            return "redirect:/admin/login";
        }

        // return "WEB-INF/jsp/admin/index.jsp"
        return "admin/index";
    }

    // 显示注册页面
    @RequestMapping("/register")
    public String register()
    {
        // 返回视图名字
        return "admin/register"; // WEB-INF/jsp/register.jsp
    }

    // 处理注册的请求
    @RequestMapping("/registerchk")
    public String registerchk(Admin admin)
    {
        boolean result = adminService.save(admin);
        if(result) {
            // 注册成功跳转登录页
            return "redirect:/admin/login";
        }
        else{
            // 注册失败重新跳回注册页
            return "rediect:/admin/register";
        }
    }

    // 显示登录页
    @RequestMapping("/login")
    public String login()
    {
        return "admin/login";
    }


    // 如果需要 请求对象 响应对象 会话对象
    // Model m
    // HttpServletRequest
    // HttpServletResponse
    // HttpSession

    // 处理登录的表单提交
    @RequestMapping("/loginchk")
    public String loginchk(String username, String password, HttpSession session)
    {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        // where username = 'zhangsan' and password = '123456';
        qw.eq("username",username).eq("password",password);
        List<Admin> list = adminService.list(qw);
        if(list.size()>0)
        {
            // 将登录信息放到session
            session.setAttribute("admin",list.get(0));
            System.out.println("登录成功,跳转首页");
            return "redirect:/admin/";
        }
        else {
            System.out.println("登录失败，跳转登录页");
            return "redirect:/admin/login";
        }
    }

    // @ResponseBody  返回的是是json内容
    @RequestMapping("/checkname")
    @ResponseBody
    public Object checkName(String username)
    {
        // 调用service 判断用户名是否可用

        Map<String,Object> result = new HashMap<>();
        result.put("result",adminService.checkName(username));
        return result;
    }
}
